const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function login(url){
  wx.login({
    success: res => {
      if (!res.code) {
        wx.showToast({
          title: "登录失败",
          icon: 'none',
          duration: 1500
        });
        return false;
      }
      wx.request({
        url: url,
        method: "GET",
        dataType: "json",
        data: { state: "xcx", code: res.code },
        success: function (data) {
          console.log(data);
          if (data.data.code == 200) {
            wx.setStorageSync('openid', data.data.data.xcx_openid);
            wx.setStorageSync('unionid', data.data.data.unionid);
            wx.setStorageSync('uid', data.data.data.id);
            return data.data.data.id;
          } else {
            wx.showToast({
              title: '发起登陆失败!失败原因:【' + data.data.message + '】',
              icon: 'none',
              duration: 3000
            });
          }
        },
        error: function (data) {
          wx.showToast({
            title: '服务器错误!发起登陆失败',
            icon: 'none',
            duration: 3000
          });
        }
      })
    }
  })
}

function getLocation(){
  wx.getLocation({
    altitude: true,
    success: function (res) {
      if (res.errMsg == 'getLocation:ok') {
        var location = {};
        location.lat = res.latitude;
        location.lon = res.longitude;
        wx.setStorageSync('location', location);
      } else {
        wx.showToast({
          title: '位置获取失败!【'+res.errMsg+'】',
          icon: "none",
          duration: 1500
        })
      }
    },
    error: function (res) {
      wx.showToast({
        title: '位置获取失败',
        icon: "none",
        duration: 1500
      })
    }
  })
  return location;
}

module.exports = {
  formatTime: formatTime,
  login:login,
  getLocation:getLocation
}
